//
//  RootViewControler.m
//  PriceOnline
//
//  Created by Le Anh Tai on 8/31/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "RootViewController.h"
#import "AdGADBanner_iPad.h"
#import "AdiAdBanner_iPad.h"
#import "AdViewManager.h"

@interface RootViewController ()

@end

static RootViewController *_shared;

@implementation RootViewController

- (id)init
{
    if (self = [super init])
    {
        _shared = self;
    }
    
    return self;
}

+ (RootViewController *)shared
{
    return _shared;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Do any additional setup after loading the view.
    [self prefersStatusBarHidden];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [self checkImportData];
    
    _websiteController = [[WebsiteViewController alloc] init];
    _websiteController.delegate = self;
    
    _navigationWebisteController = [[UINavigationController alloc] initWithRootViewController:_websiteController];
    _navigationWebisteController.view.layer.masksToBounds = NO;
    _navigationWebisteController.view.layer.shadowRadius =5;
    _navigationWebisteController.view.layer.shadowOpacity=0.5;
    [self addChildViewController:_navigationWebisteController];
    [_contentView addSubview:_navigationWebisteController.view];
//
//    _menuButton = [[BorderButton alloc] init];
//    _menuButton.alpha = 0.6f;
//    [_menuButton setImage:[UIImage imageNamed:@"icon_menu.png"] forState:UIControlStateNormal];
//    [_menuButton addTarget:self action:@selector(menuButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_menuButton];
    
    _tempSwipeRightView = [[UIView alloc] init];
    _tempSwipeRightView.backgroundColor = [UIColor clearColor];
    [_contentView addSubview:_tempSwipeRightView];
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightHandler:)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [_tempSwipeRightView addGestureRecognizer:swipeGesture];
    [_tempSwipeRightView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuButtonPressed:)]];
    
    _anchorView = [[UIView alloc] init];
    _anchorView.alpha = 0.8;
    _anchorView.backgroundColor = [UIColor grayColor];//COLOR(230, 230, 230, 0.9);
    _anchorView.layer.masksToBounds = NO;
    _anchorView.layer.cornerRadius = 4;
    _anchorView.layer.borderColor = [UIColor whiteColor].CGColor;
    _anchorView.layer.borderWidth = 1;
    _anchorView.layer.shadowRadius = 4;
    _anchorView.layer.shadowOpacity = 0.7;
    [_tempSwipeRightView addSubview:_anchorView];
    
    _menuViewController = [[MenuViewController alloc] init];
    _menuViewController.delegateMenu = self;
    _menuViewController.view.hidden = YES;
    [self.view addSubview:_menuViewController.view];
    
    [self performSelector:@selector(showMenu) withObject:nil afterDelay:0.5];
    
    [self initializeAdsMix];
}

- (void)initializeAdsMix
{
    _adsMix = [[AdsMix alloc] initWithType:AdMixTypeWeight];
    
    AdItem *item2 = [[AdItem alloc] init];
    [item2 configureWithClass:[AdGADBanner class] numberOfAllowFails:1];
    
    [_adsMix configureAds:@[item2]];
    _adsMix.delegate = self;
}

- (void)setObject:(NSManagedObject *)row key:(NSString *)key value:(id)value
{
    if (row == nil || value == nil)
    {
        return;
    }
    
    [row setValue:value forKey:key];
}

- (void)newDb:(NSString *)jsonVersion websites:(NSArray *)websites
{
    // Update db version
    NSManagedObject *dbInfoRecord = [[CoreData shared] newEntity:INFO_ENTITY];
    [self setObject:dbInfoRecord key:VERSION_KEY value:jsonVersion];
    
    // Insert website record
    NSManagedObject *markedWebsite = [[CoreData shared] newEntity:MARKED_WEBSITE_ENTITY];
    
    NSInteger order = 0;
    for (NSDictionary *dict in websites)
    {
        NSManagedObject *row = [[CoreData shared] newEntity:WEBSITE_ENTITY];
        
        [self setObject:row key:TITLE_KEY value:[dict objectForKey:TITLE_KEY]];
        [self setObject:row key:ICON_KEY value:[dict objectForKey:ICON_KEY]];
        [self setObject:row key:DESCRIPTION_KEY value:[dict objectForKey:DESCRIPTION_KEY]];
        [self setObject:row key:ORDER_KEY value:[NSNumber numberWithInteger:order++]];
        [self setObject:row key:URL_KEY value:[dict objectForKey:URL_KEY]];
        
        NSNumber *markedValue = [dict objectForKey:@"marked"];
        if ([markedValue integerValue] == 1)
        {
            [row setValue:markedWebsite forKey:MARKED_WEBSITE_KEY];
        }
    }
}

- (void)updateDb:(NSManagedObject *)dbInfoRecord jsonVersion:(NSString *)jsonVersion jsonWebsites:(NSArray *)websites
{
    [self setObject:dbInfoRecord key:VERSION_KEY value:jsonVersion];
}

- (void)checkImportData
{
    // Get db version
    NSManagedObject *dbInfoRecord = nil;
    NSString *dbVersion = @"";
    
    NSArray *infos = [[CoreData shared] fetchEntity:INFO_ENTITY];
    if (infos.count > 0)
    {
        dbInfoRecord = [infos objectAtIndex:0];
        
        if (dbInfoRecord)
        {
            dbVersion = [dbInfoRecord valueForKey:VERSION_KEY];
        }
    }
    
    // Load init data
    NSError *parsingError = nil;
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"websites" ofType:@"json"];
    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:jsonPath]
                                                     options:kNilOptions
                                                       error:&parsingError];
    
    if (parsingError)
    {
        NSLog(@"Parsing json data failed: %@", [parsingError localizedDescription]);
        return;
    }
    
    // Compare db version
    NSString *jsonVersion = [jsonData objectForKey:VERSION_KEY];
    if ([dbVersion isEqualToString:jsonVersion])
    {
        return;
    }
    
    if (dbVersion.length == 0)
    {
        [self newDb:jsonVersion websites:[jsonData objectForKey:@"websites"]];
    }
    else
    {
        [self updateDb:dbInfoRecord jsonVersion:jsonVersion jsonWebsites:[jsonData objectForKey:@"websites"]];
    }
    
    [[CoreData shared] saveContext];
}

- (void)didEnterBackground:(id)sender
{
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    NSInteger margin = 20;
    NSInteger menuButtonSize = 40;
    NSInteger anchorWid = 6;
    NSInteger anchorHei = 24;
    
    NSInteger wid = self.view.width;
    NSInteger hei = self.view.height;
    
    if (SYSTEM_VERSION_LESS_THAN(iOS_8_0))
    {
        if (Is_Landscape)
        {
            wid = self.view.height;
            hei = self.view.width;
        }
    }
    _contentView.frame = RECT(0, 0, wid, hei);
    _navigationWebisteController.view.frame = _contentView.bounds;
    _menuButton.frame = RECT(margin, margin, menuButtonSize, menuButtonSize);
    _menuViewController.view.frame = self.view.bounds;
    
    _tempSwipeRightView.frame = RECT(0, 0, 30, _contentView.height);
    _anchorView.frame = RECT(6, (_tempSwipeRightView.height - anchorHei)/2, anchorWid, anchorHei);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showMenu
{
    [_menuViewController animateOut];
}

- (void)layoutSubviews
{
//    if ([_curAds isKindOfClass:[ADBannerView class]])
//    {
//        if (Is_Landscape)
//        {
//            [(ADBannerView *)_curAds setCurrentContentSizeIdentifier:ADBannerContentSizeIdentifierLandscape];
//        }
//        else
//        {
//            [(ADBannerView *)_curAds setCurrentContentSizeIdentifier:ADBannerContentSizeIdentifierPortrait];
//        }
//    }
//    else if ([_curAds isKindOfClass:[GADBannerView class]])
//    {
//        if (Is_Landscape)
//        {
//            [(GADBannerView *)_curAds setAdSize:kGADAdSizeSmartBannerLandscape];
//        }
//        else
//        {
//            [(GADBannerView *)_curAds setAdSize:kGADAdSizeSmartBannerPortrait];
//        }
//    }    
}

#pragma mark - Delegate
- (void)menuButtonPressed:(UIButton *)sender
{
    [self showMenu];
}

- (void)swipeRightHandler:(id)sender
{
    [self showMenu];
}

#pragma mark -
- (void)menuController:(MenuViewController *)controller didSelectWebsite:(NSManagedObject *)website
{
    NSString *url = [website valueForKey:URL_KEY];
    [_websiteController.navigationController popToRootViewControllerAnimated:NO];
    
    // Special websites: Do not redirect to mobile site
    if (IS_IPHONE)
    {
        if ([url isEqualToString:@"http://diaoconline.vn/"])
        {
            url = @"http://m.diaoconline.vn/";
        }
        else if ([url isEqualToString:@"http://autopro.com.vn"])
        {
            url = @"http://m.autopro.com.vn/";
        }
    }
    
    [_websiteController loadUrl:url];
}

- (void)menuControllerWillHide:(MenuViewController *)controller
{
    [_menuViewController.view endEditing:YES];
    
    [UIView animateWithDuration:0.3 animations:^{
        _websiteController.view.frame = _contentView.bounds;
    }];
}

- (void)menuControllerWillShow:(MenuViewController *)controller
{
//    NSInteger marginTop = 60;
    
//    [UIView animateWithDuration:0.3 animations:^{
////        _websiteController.view.frame = RECT(MENU_WID + 50, marginTop, _contentView.width, _contentView.height);
//        _websiteController.view.left = MENU_WID;
//    }];
}

#pragma mark -
- (void)websiteRequireShowMenu:(WebsiteViewController *)controller
{
    [self showMenu];
}

#pragma mark -
- (void)adsMix:(AdsMix *)object didLoadAd:(BaseAds *)ad
{
//	if (_curAds)
//    {
//        [_curAds removeFromSuperview];
//    }
//    
//    _curAds = [ad getAds];
//    
//    [self layoutSubviews];
//    
//    [_websiteController addAds:_curAds];

    [[AdViewManager shared] detachAdView];
    
    [AdViewManager shared].currAdView = [ad getAds];
    [[AdViewManager shared] setupHeightForAdView];
    
    [[AdViewManager shared] attachAdView];
}

- (void)adsMix:(AdsMix *)object didUnloadAdAndRestartRequest:(BaseAds *)ad
{
    
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
